原本是在JavaScript中使用AJAX取回資料並做處理,再把處理過的資料跟表單一起送出,
但因為好像會有安全性的問題,改成在後端實作來達到一樣的效果,
有點不知道該怎麼註解,就先記錄下來
原本在前端呼叫所取回的資料:
{ "message": "檔案資訊", "files": [ { "Id": 123, "FileName": "測試圖.png", "CreateTime": "2020-05-25T14:25:44.857", "Status": "未掃毒" } ] }
需要用到的資料有"Id"跟"FileName"
在程式碼中加入類別,雖然不需用到"CreateTime"跟"Status",但回傳多少欄位就要完整宣告
public class JsonVO
{
public string message { get; set; }
public List<files> files { get; set; }
}
public class files
{
public string Id { get; set; }
public string FileName { get; set; }
public string CreateTime { get; set; }
public string Status { get; set; }
}
Using
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
主要程式碼
private String GetFileContent()
{
string content_str = string.Empty;
try
{
string rssContent = string.Empty;
ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
using (WebClient wc = new WebClient())
{
wc.Encoding = Encoding.GetEncoding("utf-8");
rssContent = wc.DownloadString(----這邊放自己的url----);
}
JsonVO jsonVO = JsonConvert.DeserializeObject<JsonVO>(rssContent);
if (jsonVO != null)
{
//取回資料並做處理
for (var i = 0; i <= jsonVO.files.Count - 1; i++)
{
content_str += "ID = " + jsonVO.files[i].Id + ",FileName = " + jsonVO.files[i].FileName;
}
}
}
catch (Exception ex)
{
}
return content_str;
}
private bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
{
if (error == System.Net.Security.SslPolicyErrors.None)
{
return true;
}
Console.WriteLine("X509Certificate [{0}] Policy Error: '{1}'", cert.Subject, error.ToString());
return false;
}